package com.hb.trade.server.center.au.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.center.au.dto.UserBlacklistDTO;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.center.au.entity.UserBlacklist;
import com.hb.core.pojo.center.au.mapper.UserBlacklistMapper;
import com.hb.trade.server.center.au.service.UserBlacklistService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.trade.server.center.au.service.UserService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户黑名单列表 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-11-30
 */
@Service
public class UserBlacklistServiceImpl extends ServiceImpl<UserBlacklistMapper, UserBlacklist> implements UserBlacklistService {

    protected final UserService userService;

    public UserBlacklistServiceImpl(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean pushToBlackList(UserBlacklistDTO userBlack) {
        if (userBlack.getUserId() != null) {
            // 查询该用户是否存在于黑名单
            boolean exists = userService.existsInBlackList(userBlack.getUserId());

            if (!exists) {
                // 不存在, 加入黑名单
                userBlack.buildBaseData(1);
                return save(userBlack);
            }

            // 已经拉黑
            return true;
        }

        // 将企业里所有用户拉黑
        if (userBlack.getOrgId() != null) {
            List<User> users = userService.listByOrgId(userBlack.getOrgId());
            for (User user : users) {
                userBlack.setUserId(user.getId());
                pushToBlackList(userBlack);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean pullOutOfBlackList(UserBlacklistDTO userBlack) {
        if (userBlack.getUserId() != null) {
            // 删除用户的黑名单记录
            QueryWrapper<UserBlacklist> wrapper = UserBlacklist.wrapper();
            wrapper.eq("user_id", userBlack.getUserId());

            return remove(wrapper);
        }

        if (userBlack.getOrgId() != null) {
            List<User> users = userService.listByOrgId(userBlack.getOrgId());
            for (User user : users) {
                userBlack.setUserId(user.getId());
                pullOutOfBlackList(userBlack);
            }
            return true;
        }
        return false;
    }
}
